package com.liuzh.kaoyanspringboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuzh.kaoyanspringboot.common.Result;
import com.liuzh.kaoyanspringboot.config.AuthAccess;
import com.liuzh.kaoyanspringboot.entity.Article;
import com.liuzh.kaoyanspringboot.service.ArticleService;
import com.liuzh.kaoyanspringboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-10
 */
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;

    // 新增或更新
    @PostMapping
    public Result save(@RequestBody Article article) {
        if (article.getId() == null) {
            article.setUserId(TokenUtils.getCurrentUser().getId());
            return Result.success(articleService.save(article));
        }
//        System.out.println(article);
//        return Result.success();
//        flushRedis(Constants.ARTICLES_KEY);
        return Result.success(articleService.reNewById(article));
    }

    // 根据 id 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
//        flushRedis(Constants.ARTICLES_KEY);
        return Result.success(articleService.removeById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
//        flushRedis(Constants.ARTICLES_KEY);
        return Result.success(articleService.removeBatchByIds(ids));
    }

    //查询所有数据
    @AuthAccess
    @GetMapping
    public Result findAll() {
        return Result.success(articleService.findAll(null));
    }

    /**
     * 根据 userId 获取他的文章
     * @param id
     * @return
     */
    @AuthAccess
    @GetMapping("/user/{id}")
    public Result findUserArticle(@PathVariable Integer id) {
        return Result.success(articleService.findAll(id));
    }

    // 根据 id 查询
    @AuthAccess
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(articleService.findById(id));
    }


    @AuthAccess
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                            @RequestParam Integer pageSize,
                            @RequestParam(defaultValue = "") String name,
                            @RequestParam(required = false,defaultValue = "0") Integer userId) {
        return Result.success(articleService.findPage(new Page<>(pageNum,pageSize),name,userId));
    }
    @AuthAccess
    @GetMapping("/Slideshow")
    public Result findSlideshow(){
        return Result.success(articleService.findSlideshow());
    }


//    // 删除缓存
//    private void flushRedis(String key) {
//        stringRedisTemplate.delete(key);
//    }


}

